package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.enums.AuditStatusEnums;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.constant.enums.ReconciliationStatusEnum;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.core.UserInfoRequest;
import com.yunyao.common.dto.ReconciliationDto;
import com.yunyao.common.dto.SoSupplyDto;
import com.yunyao.common.dto.excel.ReconciliationExcelDto;
import com.yunyao.common.dto.project.HistoryQtDto;
import com.yunyao.common.exception.BusinessException;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.StringUtils;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.mapper.BamuSoSupplyMaterialMapper;
import com.yunyao.dao.model.*;
import com.yunyao.dao.service.bamu.IBamuAuditConfirmHistoryService;
import com.yunyao.dao.service.bamu.IBamuContractWirePayService;
import com.yunyao.dao.service.bamu.IBamuPurchaseApplyService;
import com.yunyao.dao.service.bamu.IBamuReconciliationOrderMaterialService;
import com.yunyao.dao.service.bamu.IBamuReconciliationOrderService;
import com.yunyao.dao.service.bamu.IBamuReconciliationService;
import com.yunyao.dao.service.bamu.IBamuSaleContractService;
import com.yunyao.dao.service.bamu.IBamuSoSupplyMaterialService;
import com.yunyao.dao.service.bamu.IBamuSoSupplyService;
import com.yunyao.framework.audit.ReconciliationAuditHandle;
import com.yunyao.framework.dto.reconciliation.ReconciliationApprovalDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationConfirmDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationSaveDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationSubmitApprovalDto;
import com.yunyao.framework.dto.soSupply.SoSupplyMaterialDto;
import com.yunyao.framework.service.ReconciliationOrderService;
import com.yunyao.framework.service.ReconciliationService;
import com.yunyao.framework.service.SoSupplyOrderService;
import com.yunyao.framework.service.SoSupplyService;
import com.yunyao.framework.vo.reconciliation.ReconciliationVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationinfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReconciliationServiceImpl implements ReconciliationService {
    @Autowired
    private IBamuPurchaseApplyService iBamuPurchaseApplyService;
    @Autowired
    private IBamuSaleContractService iBamuSaleContractService;
    @Autowired
    private ReconciliationAuditHandle reconciliationAuditHandle;
    @Autowired
    private IBamuContractWirePayService iBamuContractWirePayService;
    @Autowired
    private IBamuReconciliationService iBamuReconciliationService;
    @Autowired
    private IBamuReconciliationOrderService iBamuReconciliationOrderService;
    @Autowired
    private IBamuSoSupplyService iBamuSoSupplyService;
    @Autowired
    private IBamuSoSupplyMaterialService iBamuSoSupplyMaterialService;
    @Autowired
    private BamuSoSupplyMaterialMapper bamuSoSupplyMaterialMapper;
    @Autowired
    private IBamuReconciliationOrderMaterialService iBamuReconciliationOrderMaterialService;
    @Autowired
    private IBamuAuditConfirmHistoryService iBamuAuditConfirmHistoryService;
    @Resource
    private SoSupplyOrderService soSupplyOrderService;
    @Resource
    private ReconciliationOrderService reconciliationOrderService;

    @Override
    public YResult<PageResult<ReconciliationVO>> pageList(ReconciliationDto reconciliationDto) {
        //构建查询条件
        LambdaQueryWrapper<BamuReconciliation> queryWrapper = new LambdaQueryWrapper<>();
        // 处理status列表
        if (reconciliationDto.getStatusList() != null && !reconciliationDto.getStatusList().isEmpty()) {
            queryWrapper.in(BamuReconciliation::getStatus, reconciliationDto.getStatusList());
        }
        queryWrapper.eq(StringUtils.isNotBlank(reconciliationDto.getContractId()), BamuReconciliation::getContractId, reconciliationDto.getContractId())
                .eq(StringUtils.isNotBlank(reconciliationDto.getProjectId()), BamuReconciliation::getProjectId, reconciliationDto.getProjectId())
                .eq(StringUtils.isNotBlank(reconciliationDto.getSupplierDeptId()), BamuReconciliation::getSupplierDeptId, reconciliationDto.getSupplierDeptId())
                .eq(StringUtils.isNotBlank(reconciliationDto.getContractMethod()), BamuReconciliation::getContractMethod, reconciliationDto.getContractMethod())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuReconciliation::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuReconciliation::getSupplierDeptId, BaseContext.getSupplierList())
                .like(StringUtils.isNotBlank(reconciliationDto.getProjectName()), BamuReconciliation::getProjectName, reconciliationDto.getProjectName())
                .like(StringUtils.isNotBlank(reconciliationDto.getSupplierDeptName()), BamuReconciliation::getSupplierDeptName, reconciliationDto.getSupplierDeptName())
                .like(StringUtils.isNotBlank(reconciliationDto.getContractName()), BamuReconciliation::getContractName, reconciliationDto.getContractName())
                .like(StringUtils.isNotBlank(reconciliationDto.getContractNo()), BamuReconciliation::getContractNo, reconciliationDto.getContractNo())
                .ge(StringUtils.isNotBlank(reconciliationDto.getReconciliationStartDate()), BamuReconciliation::getReconciliationStartDate, ConvertUtil.getString2Date(reconciliationDto.getReconciliationStartDate()))
                .le(StringUtils.isNotBlank(reconciliationDto.getReconciliationEndDate()), BamuReconciliation::getReconciliationEndDate, ConvertUtil.getString2Date(reconciliationDto.getReconciliationEndDate()))
                .eq(reconciliationDto.getStatus() != null, BamuReconciliation::getStatus, reconciliationDto.getStatus())
                .eq(BamuReconciliation::getIsDeleted, 0)
                .orderByDesc(BamuReconciliation::getCreatedAt);
        // 分页查询
        IPage<BamuReconciliation> soSupplyPage = new Page<>(reconciliationDto.getPageIndex(), reconciliationDto.getPageSize());
        soSupplyPage = iBamuReconciliationService.page(soSupplyPage, queryWrapper);
        // 处理查询结果
        if (CollectionUtils.isEmpty(soSupplyPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }
//        // 转换为VO对象列表
//        List<ReconciliationVO> reconciliationVOList = daoToVoList(soSupplyPage.getRecords());
        // 预先查询BamuContractWirePay对象
        List<String> contractIds = soSupplyPage.getRecords().stream()
                .map(BamuReconciliation::getContractId)
                .distinct()
                .collect(Collectors.toList());
        Map<String, BamuContractWirePay> contractWirePayMap = iBamuContractWirePayService.mapByContractIdList(contractIds);

        // 转换为VO对象列表
        List<ReconciliationVO> reconciliationVOList = daoToVoList(soSupplyPage.getRecords(), contractWirePayMap);
        // 返回分页结果
        return YResult.success(new PageResult<>(reconciliationVOList, soSupplyPage.getCurrent(), soSupplyPage.getSize(), soSupplyPage.getPages(), soSupplyPage.getTotal()));
    }

    @Override
    public BigDecimal getHistoryPrice(@NotBlank String contractId) {
        List<BamuReconciliation> list = iBamuReconciliationService.lambdaQuery()
                .eq(BamuReconciliation::getContractId, contractId)
                .eq(BamuReconciliation::getStatus, ReconciliationStatusEnum.CLOUD_ACQUISITION_CONFIRMATION_COMPLETE)
                .eq(BamuReconciliation::getIsDeleted, DataDeletedStatus.NO.getType())
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return BigDecimal.ZERO;
        }
        return list.stream()
                .map(BamuReconciliation::getReconciliationPrice)
                .reduce(BigDecimal::add)
                .orElse(BigDecimal.ZERO);
    }


    @Override
    public BigDecimal getTaxTotalPrice(HistoryQtDto dto) {
        List<String> soSupply = reconciliationOrderService.getSoSupply(dto.getContractId());
        if(CollectionUtils.isEmpty(soSupply)){
            return BigDecimal.ZERO;
        }
        return soSupplyOrderService.getBySupplyId(soSupply);
    }

    private List<ReconciliationVO> daoToVoList(List<BamuReconciliation> records, Map<String, BamuContractWirePay> contractWirePayMap) {
        return records.stream().map(record -> daoToVo(record, contractWirePayMap)).collect(Collectors.toList());
    }

    private ReconciliationVO daoToVo(BamuReconciliation bamuReconciliation, Map<String, BamuContractWirePay> contractWirePayMap) {
        ReconciliationVO reconciliationVO = new ReconciliationVO();
        BeanUtils.copyProperties(bamuReconciliation, reconciliationVO);
        String auditStatus = bamuReconciliation.getAuditStatus();
        String processInstanceId = bamuReconciliation.getProcessInstanceId();
        String modelSchemeInfoId = bamuReconciliation.getModelSchemeInfoId();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(auditStatus)
                && org.apache.commons.lang3.StringUtils.equals(auditStatus, AuditStatusEnums.AUDIT.getType().toString())
                && org.apache.commons.lang3.StringUtils.isNotBlank(modelSchemeInfoId)
                && org.apache.commons.lang3.StringUtils.isNotBlank(processInstanceId)) {
            reconciliationVO.setAuditButton(reconciliationAuditHandle.userIsAuditButton(modelSchemeInfoId, processInstanceId));
        }
        BamuContractWirePay wirePay = contractWirePayMap.get(bamuReconciliation.getContractId());
        if (wirePay != null) {
            reconciliationVO.setPriceType(wirePay.getPriceType());
            reconciliationVO.setPaymentCycle(wirePay.getPaymentCycle());
        }
        //获取合同id
        String contractId = bamuReconciliation.getContractId();
        //根据合同id，获取历史对账单
        List<BamuReconciliation> list = iBamuReconciliationService.lambdaQuery()
                .eq(BamuReconciliation::getContractId, contractId)
                .eq(BamuReconciliation::getIsDeleted, DataDeletedStatus.NO.getType()).list();
        if(CollectionUtils.isNotEmpty(list)){
            List<String> idList = list.stream().map(BamuReconciliation::getId).distinct().toList();
            //查询材料表，获取所有结算单的历史结算金额
            List<BamuReconciliationOrderMaterial> resultList = iBamuReconciliationOrderMaterialService.lambdaQuery()
                    .in(BamuReconciliationOrderMaterial::getReconciliationId, idList)
                    .list();
            if(CollectionUtils.isNotEmpty(resultList)){
                BigDecimal sum = resultList.stream().map(BamuReconciliationOrderMaterial::getReconciliationPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                reconciliationVO.setHistoryTotalPrice(sum);
            }
        }
        return reconciliationVO;
    }


    @Override
    public YResult<ReconciliationinfoVO> getReconliationById(Long id) {
        LambdaQueryWrapper<BamuReconciliation> wrapper = new LambdaQueryWrapper<BamuReconciliation>()
                .eq(BamuReconciliation::getId, id);
        BamuReconciliation bamuReconciliation = iBamuReconciliationService.getOne(wrapper);
        // 处理查询结果
        if (Objects.isNull(bamuReconciliation)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        return YResult.success(daoToInfoVO(bamuReconciliation));
    }

    @Override
    public YResult<ReconciliationinfoVO> getInfo(ReconciliationDto reconciliationDto) {
        // 提取传入参数中的结算单ID
        String id = reconciliationDto.getId();

        // 通过ID查询对应的结算单，同时确保查询到的结算单未被删除
        BamuReconciliation bamuReconciliationSettlement =
                iBamuReconciliationService.getByIdNoDelete(id);

        // 如果查询不到对应的结算单或结算单已被删除，则返回一个表示没有数据的错误结果
        if (Objects.isNull(bamuReconciliationSettlement)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 如果查询成功，则将结算单信息转换为特定的值对象，并返回一个包含该信息的成功结果
        return YResult.success(daoToInfoVO(bamuReconciliationSettlement));
    }


    private ReconciliationinfoVO daoToInfoVO(BamuReconciliation bamuReconciliation) {
        ReconciliationinfoVO reconciliationinfoVO = new ReconciliationinfoVO();
        BeanUtils.copyProperties(bamuReconciliation, reconciliationinfoVO);
        //获取合同id
        String contractId = bamuReconciliation.getContractId();
        //根据合同id，获取历史对账单
        List<BamuReconciliation> list = iBamuReconciliationService.lambdaQuery()
                .eq(BamuReconciliation::getContractId, contractId)
                .lt(BamuReconciliation::getCreatedAt,bamuReconciliation.getCreatedAt())
                .eq(BamuReconciliation::getIsDeleted, DataDeletedStatus.NO.getType()).list();
        if(CollectionUtils.isNotEmpty(list)){
            List<String> idList = list.stream().map(BamuReconciliation::getId).distinct().toList();
            //查询材料表，获取所有结算单的历史结算金额
            List<BamuReconciliationOrderMaterial> resultList = iBamuReconciliationOrderMaterialService.lambdaQuery()
                    .in(BamuReconciliationOrderMaterial::getReconciliationId, idList)
                    .list();
            if(CollectionUtils.isNotEmpty(resultList)){
                BigDecimal sum = resultList.stream().map(BamuReconciliationOrderMaterial::getReconciliationPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                reconciliationinfoVO.setHistoryTotalPrice(sum);
            }
        }
        return reconciliationinfoVO;
    }


    @Override
    public YResult<String> saveInfo(ReconciliationSaveDto saveDto) {
        BamuReconciliation bamuReconciliation = new BamuReconciliation();
//        LambdaQueryWrapper<BamuSaleContract> wrapper = new LambdaQueryWrapper<BamuSaleContract>().eq(BamuSaleContract::getId, saveDto.getContractId())
//                .eq(BamuSaleContract::getIsDeleted, DataDeletedStatus.NO.getType());
//
//        // 调用服务方法查询合同信息
//        BamuSaleContract bamuSaleContract = iBamuSaleContractService.getOne(wrapper);
        if (saveDto.getId() == null) {
            // 自动生成19位随机数字ID
            Random random = new Random();
            // 初始化为空字符串
            StringBuilder idBuilder = new StringBuilder();
            // 生成19位数字，如果不足前面补0
            for (int i = 0; i < 19; i++) {
                // 生成一个0-9之间的随机数
                int randomDigit = random.nextInt(10);
                // 添加到StringBuilder
                idBuilder.append(randomDigit);
            }
            String randomId = idBuilder.toString();

            // 假设BamuReconciliation有一个setId的方法
            bamuReconciliation.setId(randomId);
            BeanUtils.copyProperties(saveDto, bamuReconciliation);
            bamuReconciliation.setCreatedAt(ConvertUtil.getString2Date(saveDto.getCreatedAt()));
            bamuReconciliation.setReconciliationStartDate(ConvertUtil.getString2Date(saveDto.getReconciliationStartDate()));
            bamuReconciliation.setReconciliationEndDate(ConvertUtil.getString2Date(saveDto.getReconciliationEndDate()));
        } else {
            BeanUtils.copyProperties(saveDto, bamuReconciliation);
            bamuReconciliation.setCreatedAt(ConvertUtil.getString2Date(saveDto.getCreatedAt()));
            bamuReconciliation.setReconciliationStartDate(ConvertUtil.getString2Date(saveDto.getReconciliationStartDate()));
            bamuReconciliation.setReconciliationEndDate(ConvertUtil.getString2Date(saveDto.getReconciliationEndDate()));
        }
        SoSupplyDto soSupplyDto = new SoSupplyDto();
        soSupplyDto.setContractId(saveDto.getContractId());

//        List<SoSupplyVO> bamuSoSupply = (List<SoSupplyVO>) soSupplyServiceIml.pageList(soSupplyDto);
//        YResult<PageResult<SoSupplyVO>> result = soSupplyServiceIml.pageList(soSupplyDto);
//        PageResult<SoSupplyVO> pageResult = result.getData();
//        List<SoSupplyVO> bamuSoSupply = pageResult.getList();
        LambdaQueryWrapper<BamuSoSupply> queryWrapper = new LambdaQueryWrapper<BamuSoSupply>()
                .eq(BamuSoSupply::getContractId, soSupplyDto.getContractId())
                .eq(BamuSoSupply::getIsDeleted, DataDeletedStatus.NO.getType());
        List<BamuSoSupply> bamuSoSupply = iBamuSoSupplyService.list(queryWrapper);
        BigDecimal rreconciliationtaxTotalPrice = BigDecimal.ZERO; // 初始化为0
        for (int i = 0; i < bamuSoSupply.size(); i++) {
            // 累加taxTotalPrice到统计变量中
            rreconciliationtaxTotalPrice = rreconciliationtaxTotalPrice.add(bamuSoSupply.get(i).getTaxTotalPrice());
            LambdaQueryWrapper<BamuReconciliationOrder> queryWrapper1 = new LambdaQueryWrapper<BamuReconciliationOrder>()
                    .eq(BamuReconciliationOrder::getSupplyId, bamuSoSupply.get(i).getId())
                    .eq(BamuReconciliationOrder::getOrderSn, bamuSoSupply.get(i).getOrderSn())
                    .eq(BamuReconciliationOrder::getReconciliationId, bamuReconciliation.getId());
            BamuReconciliationOrder bamuReconciliationOrder1 = iBamuReconciliationOrderService.getOne(queryWrapper1);
            if (Objects.isNull(bamuReconciliationOrder1)) {
                BamuReconciliationOrder bamuReconciliationOrder = new BamuReconciliationOrder();
                BeanUtils.copyProperties(bamuSoSupply.get(i), bamuReconciliationOrder);
                bamuReconciliationOrder.setSupplyId(bamuSoSupply.get(i).getId());
                bamuReconciliationOrder.setReconciliationId(bamuReconciliation.getId());
                // 自动生成19位随机数字ID
                Random random = new Random();
                // 初始化为空字符串
                StringBuilder idBuilder = new StringBuilder();
                // 生成19位数字，如果不足前面补0
                for (int x = 0; x < 19; x++) {
                    // 生成一个0-9之间的随机数
                    int randomDigit1 = random.nextInt(10);
                    // 添加到StringBuilder
                    idBuilder.append(randomDigit1);
                }
                String randomId1 = idBuilder.toString();
                bamuReconciliationOrder.setId(randomId1);

                iBamuReconciliationOrderService.saveOrUpdate(bamuReconciliationOrder);
            }
        }
        bamuReconciliation.setReconciliationPrice(rreconciliationtaxTotalPrice);
        bamuReconciliation.setSupplyIncludingTaxTotalPrice(rreconciliationtaxTotalPrice);
        iBamuReconciliationService.saveOrUpdate(bamuReconciliation);
        LambdaQueryWrapper<BamuPurchaseApply> queryWrapper2 = new LambdaQueryWrapper<BamuPurchaseApply>()
                .eq(BamuPurchaseApply::getContractId, bamuReconciliation.getContractId());
        List<BamuPurchaseApply> bamuPurchaseApply = iBamuPurchaseApplyService.list(queryWrapper2);
        SoSupplyMaterialDto soSupplyOrderDto = new SoSupplyMaterialDto();
        soSupplyOrderDto.setIdList(saveDto.getSoSupplyIdList());
        if (soSupplyOrderDto.getIdList() != null && soSupplyOrderDto.getIdList().size() > 0) {
            LambdaQueryWrapper<BamuSoSupplyMaterial> Wrapper = new LambdaQueryWrapper<BamuSoSupplyMaterial>()
                    .in(BamuSoSupplyMaterial::getSupplyId, soSupplyOrderDto.getIdList());
            List<BamuSoSupplyMaterial> bamuSoSupplyMaterials = bamuSoSupplyMaterialMapper.selectList(Wrapper);
            for (int i = 0; i < bamuSoSupplyMaterials.size(); i++) {
                BamuReconciliationOrderMaterial bamuReconciliationOrderMaterial = new BamuReconciliationOrderMaterial();
                BeanUtils.copyProperties(bamuSoSupplyMaterials.get(i), bamuReconciliationOrderMaterial);
                bamuReconciliationOrderMaterial.setReconciliationId(bamuReconciliation.getId());
                if (bamuPurchaseApply != null) { // 添加非空判断
                    bamuReconciliationOrderMaterial.setReconciliationOrderSn(bamuPurchaseApply.get(1).getOrderSn());
                }
                iBamuReconciliationOrderMaterialService.saveOrUpdate(bamuReconciliationOrderMaterial);
            }
        }


//       return YResult.success(bamuReconciliation.getId());
        // 批量保存或更新对账结算订单信息
//        reconciliationOrderSaveBatch(saveDto.getSoSupplyIdList()
//                , saveDto.getId());
        // 返回成功结果，携带结算ID
        return YResult.success(bamuReconciliation.getId());
    }

    private void checkSaveData(ReconciliationSaveDto saveDto) {
        String contractId = saveDto.getContractId();
        if (org.apache.commons.lang3.StringUtils.isBlank(contractId)) {
            throw new BusinessException("合同参数必传");
        }
        BamuSaleContract bamuSaleContract = iBamuSaleContractService.getByIdNoDelete(contractId);
        if (Objects.isNull(bamuSaleContract)) {
            throw new BusinessException("未查询可用合同");
        }
        String reconciliationStartDate = saveDto.getReconciliationStartDate();
        if (org.apache.commons.lang3.StringUtils.isBlank(reconciliationStartDate)) {
            throw new BusinessException("对账开始时间参数必传");
        }
        String reconciliationEndDate = saveDto.getReconciliationEndDate();
        if (org.apache.commons.lang3.StringUtils.isBlank(reconciliationEndDate)) {
            throw new BusinessException("对账结束时间参数必传");
        }
        List<String> soSupplyIdList = saveDto.getSoSupplyIdList();
        if (CollectionUtils.isEmpty(soSupplyIdList)) {
            throw new BusinessException("清单参数必传");
        }
        List<String> distinctSoSupplyIdList =
                soSupplyIdList.stream().distinct().toList();
        if (distinctSoSupplyIdList.size() != soSupplyIdList.size()) {
            throw new BusinessException("清单参数重复");
        }
    }

    private void saveSaleContractInfo(String contractId,
                                      BamuReconciliation reconciliation) {
        BamuSaleContract saleContract = iBamuSaleContractService.getByIdNoDelete(contractId);
        if (Objects.isNull(saleContract)) {
            return;
        }
        reconciliation.setContractId(contractId);
        reconciliation.setContractNo(saleContract.getContractNo());
        reconciliation.setContractName(saleContract.getContractName());
        reconciliation.setPurchaseDeptId(saleContract.getPurchaseDeptId());
        reconciliation.setPurchaseDeptName(saleContract.getPurchaseDeptName());
        reconciliation.setPurchaseDeptName(saleContract.getPurchaseDeptName());
        reconciliation.setProjectId(saleContract.getProjectId());
        reconciliation.setProjectName(saleContract.getProjectName());
        reconciliation.setSupplyDeptId(saleContract.getSupplyDeptId());
        reconciliation.setSupplyDeptName(saleContract.getSupplyDeptName());
        reconciliation.setSupplierDeptId(saleContract.getSupplierDeptId());
        reconciliation.setSupplierDeptName(saleContract.getSupplierDeptName());
        reconciliation.setContractMethod(saleContract.getContractMethod());
        reconciliation.setProjectDeptId(saleContract.getProjectDeptId());
        reconciliation.setProjectDeptName(saleContract.getProjectDeptName());
//        reconciliation.setContractRebatePoints(saleContract.getContractRebatePoints());
//        BigDecimal contractRebatePoints = saleContract.getContractRebatePoints();
//        BigDecimal contractTotalRealPrice = saleContract.getContractTotalRealPrice();
//        if (Objects.nonNull(contractRebatePoints) && Objects.nonNull(contractTotalRealPrice)
//                && contractRebatePoints.doubleValue()>BigDecimal.ZERO.doubleValue() &&  contractTotalRealPrice.doubleValue()>BigDecimal.ZERO.doubleValue()){
//            reconciliation.setContractRebatePrice(contractRebatePoints.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).multiply(contractTotalRealPrice));
//        }

    }

    private void spReconciliationSettlementOrderBatch(List<String> sosupplyIdList,
                                                      String reconciliationId) {
        // 检查对账ID列表是否为空，为空则直接返回
        if (CollectionUtils.isEmpty(sosupplyIdList)) {
            throw new BusinessException("清单参数必传");
        }
        iBamuSoSupplyService.updByIdsStatus(sosupplyIdList, "1", reconciliationId);
        // 根据对账单ID列表查询已删除的对账单信息
        List<BamuSoSupply> bamuSoSupplyList =
                iBamuSoSupplyService.listByIdsDeleted(sosupplyIdList);
        if (CollectionUtils.isEmpty(bamuSoSupplyList)) {
            throw new BusinessException("清单信息异常");
        }
        // 根据对账ID列表查询已删除的结算单列表
        List<BamuReconciliationOrder> reconciliationOrderList =
                iBamuReconciliationOrderService.listByReconciliationSettlementIdDeleted(reconciliationId);
        List<String> oldSosupplyIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(reconciliationOrderList)) {
            List<String> deleteIdList =
                    reconciliationOrderList.stream().map(BamuReconciliationOrder::getSupplyId)
                            .filter(supplyId -> !sosupplyIdList.contains(supplyId)).toList();
            if (CollectionUtils.isNotEmpty(deleteIdList)) {
                iBamuReconciliationOrderService.deletedByReconciliationIdList(deleteIdList);
                iBamuReconciliationOrderMaterialService.deletedByReconciliationIdList(deleteIdList);
            }
            oldSosupplyIdList =
                    reconciliationOrderList.stream().map(BamuReconciliationOrder::getSupplyId).toList();
        }
        List<String> finalOldPodupplyIdList = oldSosupplyIdList;
        List<String> filterPosupplyIdList =
                sosupplyIdList.stream().filter(x -> !finalOldPodupplyIdList.contains(x)).toList();
        if (CollectionUtils.isEmpty(filterPosupplyIdList)) {
            return;
        }
        List<BamuSoSupply> posupplyList =
                bamuSoSupplyList.stream().filter(x -> filterPosupplyIdList.contains(x.getId())).toList();
        // 批量保存对账单与结算单的关联关系
        reconciliationSettlementSaveBatch(posupplyList, reconciliationId);
    }

    private BamuReconciliationOrder reconciliationToSettlementOrder(BamuSoSupply bamuPoSupply, String reconciliationId) {
        // 初始化一个新的结算单对象
        BamuReconciliationOrder spReconciliationOrder =
                new BamuReconciliationOrder();
        // 复制对账结果的属性到结算单对象
        BeanUtils.copyProperties(bamuPoSupply, spReconciliationOrder);
        // 设置结算单的唯一ID
        spReconciliationOrder.setReconciliationId(reconciliationId);
        // 保留原对账单的ID
        spReconciliationOrder.setSupplyId(bamuPoSupply.getId());
        // 将结算单对象的ID设置为null，标记这是一个新的记录
        spReconciliationOrder.setId(null);
        // 返回转换后的结算单对象
        return spReconciliationOrder;
    }

    private void reconciliationSettlementSaveBatch(List<BamuSoSupply> poSupplyList,
                                                   String reconciliationId) {
        // 将对账单信息转换为对账结算单信息列表
        List<BamuReconciliationOrder> spReconciliationOrderList =
                poSupplyList.stream().map(x -> reconciliationToSettlementOrder(x,
                        reconciliationId)).collect(Collectors.toList());
        // 批量保存对账结算单信息
        iBamuReconciliationOrderService.saveBatch(spReconciliationOrderList);
        // 遍历对账结算单信息列表，处理每张对账单的明细信息
        for (BamuReconciliationOrder bamuSpReconciliationOrder :
                spReconciliationOrderList) {
            // 获取当前对账结算单的唯一标识
            String id = bamuSpReconciliationOrder.getId();
            // 获取当前对账结算单关联的对账单ID
            String posupplyID = bamuSpReconciliationOrder.getSupplyId();
            // 根据对账单ID查询对应的对账明细信息
            List<BamuSoSupplyMaterial> poSupplyMaterialList =
                    iBamuSoSupplyMaterialService.listByReconciliationId(posupplyID);
            // 如果对账明细信息列表不为空，则进行处理
            if (CollectionUtils.isNotEmpty(poSupplyMaterialList)) {
                // 将对账明细信息转换为对账结算明细信息列表
                List<BamuReconciliationOrderMaterial> bamuSpReconciliationOrderMaterialList =
                        poSupplyMaterialList.stream().map(x -> reconciliationToSettlementOrderMaterial(x, reconciliationId, id)).toList();
                // 批量保存对账结算明细信息
                iBamuReconciliationOrderMaterialService.saveBatch(bamuSpReconciliationOrderMaterialList);
            }
        }
    }

    private BamuReconciliationOrderMaterial reconciliationToSettlementOrderMaterial(BamuSoSupplyMaterial bamuPoSupplyMaterial,
                                                                                    String reconciliationId,
                                                                                    String reconciliationOrderId) {
        // 初始化一个新的结算单材料对象
        BamuReconciliationOrderMaterial spReconciliationOrderMaterial =
                new BamuReconciliationOrderMaterial();
        LambdaQueryWrapper<BamuReconciliationOrder> queryWrapper = new LambdaQueryWrapper<BamuReconciliationOrder>()
                .eq(BamuReconciliationOrder::getReconciliationId, reconciliationId)
                .last("limit 1");
        BamuReconciliationOrder reconciliationOrder = iBamuReconciliationOrderService.getOne(queryWrapper);
        // 复制对账单材料对象的属性到结算单材料对象
        BeanUtils.copyProperties(bamuPoSupplyMaterial,
                spReconciliationOrderMaterial);
        BigDecimal excludingTaxUnitPrice = spReconciliationOrderMaterial.getIncludingTaxUnitPrice().divide(new BigDecimal("1").add(spReconciliationOrderMaterial.getTax()), RoundingMode.HALF_UP);
        spReconciliationOrderMaterial.setExcludingTaxUnitPrice(excludingTaxUnitPrice);
        spReconciliationOrderMaterial.setReconciliationNum(bamuPoSupplyMaterial.getComfirmSupplyNum());
        spReconciliationOrderMaterial.setReconciliationPrice(bamuPoSupplyMaterial.getIncludingTaxTotalPrice());
        // 设置结算单ID
        spReconciliationOrderMaterial.setReconciliationId(reconciliationId);
        // 设置结算单项ID
        spReconciliationOrderMaterial.setReconciliationOrderId(reconciliationOrderId);
        spReconciliationOrderMaterial.setReconciliationOrderSn(reconciliationOrder.getOrderSn());
        // 为新生成的结算单材料对象设置一个空的ID，表示它是一个新对象
        spReconciliationOrderMaterial.setId(null);
        // 返回新的结算单材料对象
        return spReconciliationOrderMaterial;
    }

    public void findByIdUpdSpReconciliation(@Valid @NotNull List<BamuReconciliationOrderMaterial> spReconciliationOrderMaterials) {
        spReconciliationOrderMaterials.forEach(e -> {
            e.setIncludingTaxTotalPrice(e.getIncludingTaxUnitPrice().multiply(e.getSupplyNum()));
        });
        iBamuReconciliationOrderMaterialService.updateBatchById(spReconciliationOrderMaterials);
    }

    @Override
    public YResult<String> save(ReconciliationSaveDto saveDto) {
        checkSaveData(saveDto);
        // 初始化结算实体对象
        BamuReconciliation spReconciliation = new BamuReconciliation();
        spReconciliation.setId(saveDto.getId());
        String contractId = saveDto.getContractId();
        saveSaleContractInfo(contractId, spReconciliation);
        // 解析并设置对账开始日期
        spReconciliation.setReconciliationStartDate(ConvertUtil.getString2Date(saveDto.getReconciliationStartDate()
        ));
        // 解析并设置对账结束日期
        spReconciliation.setReconciliationEndDate(ConvertUtil.getString2Date(saveDto.getReconciliationEndDate()));
        spReconciliation.setStatus(0);
        //设置历史金额
        if (saveDto.getId() == null) {
            spReconciliation.setHistoryTotalPrice(addIdentification(saveDto.getContractId()));
        } else {
            spReconciliation.setHistoryTotalPrice(saveDto.getHistoryTotalPrice());
        }
//        // 解析并设置结算日期
//        spReconciliation.setSettlementDate(DateUtils.parseDate(saveDto.getSettlementDate(),
//                DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
        // 保存或更新结算信息
        iBamuReconciliationService.saveOrUpdate(spReconciliation);

        // 批量保存对账结算订单
        spReconciliationSettlementOrderBatch(saveDto.getSoSupplyIdList(),
                spReconciliation.getId());
        updateSupplyInfo(spReconciliation.getId(), spReconciliation.getContractId());

        //修改对账信息
        if (CollectionUtils.isNotEmpty(saveDto.getSpReconciliationOrderMaterials())) {
            findByIdUpdSpReconciliation(saveDto.getSpReconciliationOrderMaterials());
        }
        // 返回成功结果，包含结算ID
        return YResult.success(spReconciliation.getId());
    }

    /**
     * 对账-获取历史金额信息
     *
     * @param contractId
     * @return
     */
    public BigDecimal addIdentification(String contractId) {
        List<String> soSupplyIds = reconciliationOrderService.getSoSupply(contractId);
        if (CollectionUtils.isEmpty(soSupplyIds)) {
            return BigDecimal.ZERO;
        }
        List<BamuSoSupplyMaterial> list = iBamuSoSupplyMaterialService.lambdaQuery()
                .eq(BamuSoSupplyMaterial::getIsDeleted, DataDeletedStatus.NO.getType())
                .in(BamuSoSupplyMaterial::getSupplyId, soSupplyIds)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return BigDecimal.ZERO;
        }
        return list.stream()
                .map(BamuSoSupplyMaterial::getIncludingTaxTotalPrice)
                .reduce(BigDecimal::add)
                .orElse(BigDecimal.ZERO);
    }


    private void updateSupplyInfo(String id, String contractId) {
        BamuReconciliation reconciliation = new BamuReconciliation();
        reconciliation.setId(id);
        List<BamuSoSupply> poSupplyList =
                iBamuSoSupplyService.listByReconciliationSettlementIdDeleted(id, contractId);
        if (CollectionUtils.isEmpty(poSupplyList)) {
            return;
        }
        int supplyNum = poSupplyList.size();
//                spReconciliationOrderList.stream().map(BamuSpReconciliationOrder::getSupplyNum).mapToInt(Integer::intValue).sum();
        double supplyIncludingTaxTotalPrice =
                poSupplyList.stream().map(BamuSoSupply::getTaxTotalPrice).mapToDouble(BigDecimal::doubleValue).sum();
//        double reconciliationPrice =
//                poSupplyList.stream().map(BamuPoSupply::getReconciliationPrice).mapToDouble(BigDecimal::doubleValue).sum();
        reconciliation.setSupplyNum(supplyNum);
        reconciliation.setReconciliationNum(BigDecimal.valueOf(poSupplyList.size()));
        reconciliation.setSupplyIncludingTaxTotalPrice(BigDecimal.valueOf(supplyIncludingTaxTotalPrice));
//        reconciliation.setSettlementNum(spReconciliationSettlementOrderList.size());
        reconciliation.setReconciliationPrice(BigDecimal.valueOf(supplyIncludingTaxTotalPrice));
        iBamuReconciliationService.updateById(reconciliation);
    }

    @Override
    @Transactional
    public YResult<Boolean> deleteInfo(ReconciliationSaveDto reconciliationDto) {
        // 根据ID查询要删除的BamuPoSupply对象
        BamuReconciliation bamuReconciliation = iBamuReconciliationService.getById(Long.valueOf(reconciliationDto.getId()));

        // 如果对象不存在，返回错误信息
        if (bamuReconciliation == null) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        //修改已选择的验证清单状态
        iBamuSoSupplyService.updByIdsSupplyStatus(bamuReconciliation.getContractId(), reconciliationDto.getId());
        return iBamuReconciliationService.removeById(Long.valueOf(reconciliationDto.getId())) ? YResult.success(true) : YResult.error(ResultMsgEnum.ERROR);
    }

//

    @Override
    public YResult<String> submitApproval(ReconciliationSubmitApprovalDto approvalDto) {
        try {
            // 调用审批处理方法来提交审批
            reconciliationAuditHandle.submit(approvalDto.getId());
            // 如果审批提交成功，返回一个包含审批ID的成功结果
            return YResult.success(approvalDto.getId());
        } catch (Exception e) {
            // 如果审批提交过程中发生异常，记录错误日志
            log.error("提交审批异常", e);
            // 如果审批提交过程中发生异常，返回错误结果，包含异常信息
            return YResult.error(ResultMsgEnum.SUBMIT_APPROVAL_ERROR);
        }
    }

    @Override
    public YResult<String> approval(ReconciliationApprovalDto approvalDto) {
        // 尝试调用审批处理方法执行采购合同审批操作
        try {
            reconciliationAuditHandle.approval(approvalDto);
            // 审批成功，返回成功结果对象，携带审批ID
            return YResult.success(approvalDto.getId());
        } catch (Exception e) {
            // 审批过程中发生异常，返回错误结果，携带异常信息
            return YResult.error(ResultMsgEnum.APPROVAL_ERROR);
        }
    }

    @Override
    public YResult<String> confirm(ReconciliationConfirmDto reconciliationConfirmDto) {
        // 提取DTO中的ID和其他确认信息
        String id = reconciliationConfirmDto.getId();
        String reconciliationconfirmDate =
                reconciliationConfirmDto.getReconciliationConfirmDate();
        String reconciliationConfirmPerson =
                reconciliationConfirmDto.getReconciliationConfirmPerson();
        String reconciliationFile =
                reconciliationConfirmDto.getReconciliationFile();
        String reconciliationConfirmMark =
                reconciliationConfirmDto.getReconciliationConfirmMark();
        boolean isConfirmReconciliation = reconciliationConfirmDto.getReconciliationConfirmStatus();


        if (!ConvertUtil.isValidNotEmptyJson(reconciliationFile)) {
            reconciliationFile = "[]";
        }
        // 根据ID获取结算信息，确保未被删除
        BamuReconciliation reconciliation =
                iBamuReconciliationService.getByIdNoDelete(id);
        if (Objects.isNull(reconciliation)) {
            // 若找不到结算信息，返回错误结果
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算状态是否为供应商已确认
        Integer status = reconciliation.getStatus();
        if (status != ReconciliationStatusEnum.CONFIRMED_BY_SUPPLIER.getType()) {
            // 若状态不正确，返回错误结果
            return YResult.error("项目对账状态非待确认");
        }
        int reconciliationStatus = isConfirmReconciliation ?
                ReconciliationStatusEnum.CONFIRMED_BY_CLOUD_ACQUISITION.getType() :
                ReconciliationStatusEnum.SUPPLIER_CONFIRMATION_REJECTION.getType();
        // 更新结算状态为云采购已确认，并保存确认凭证和标记
        reconciliation.setStatus(reconciliationStatus);
        reconciliation.setReconciliationConfirmDate(ConvertUtil.getString2Date(reconciliationconfirmDate));
        reconciliation.setReconciliationConfirmPerson(reconciliationConfirmPerson);
        reconciliation.setReconciliationFile(reconciliationFile);
        reconciliation.setReconciliationConfirmMark(reconciliationConfirmMark);
        iBamuReconciliationService.updateById(reconciliation);

        // 记录审核确认历史
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        Date date = ConvertUtil.getString2Date(reconciliationconfirmDate);
        iBamuAuditConfirmHistoryService.insertRecord(reconciliation.getId(), date
                , reconciliation.getReconciliationPrice(),
                reconciliationFile,
                reconciliationConfirmMark,
                reconciliationStatus, "1",
                userInfo.getRealName());

        // 返回操作成功的结果
        return YResult.success(reconciliation.getId());
    }

    @Override
    public YResult<String> check(ReconciliationConfirmDto reconciliationConfirmDto) {
        // 提取DTO中的ID和其他确认信息
        String id = reconciliationConfirmDto.getId();
        String reconciliationconfirmDate =
                reconciliationConfirmDto.getReconciliationConfirmDate();
        String reconciliationFile =
                reconciliationConfirmDto.getReconciliationFile();
        String reconciliationConfirmMark =
                reconciliationConfirmDto.getReconciliationConfirmMark();

        if (!ConvertUtil.isValidNotEmptyJson(reconciliationFile)) {
            reconciliationFile = "[]";
        }
        // 根据ID获取结算信息，确保未被删除
        BamuReconciliation reconciliation =
                iBamuReconciliationService.getByIdNoDelete(id);
        if (Objects.isNull(reconciliation)) {
            // 若找不到结算信息，返回错误结果
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算状态是否为供应商已确认
        Integer status = reconciliation.getStatus();
        if (status != ReconciliationStatusEnum.TO_BE_CHECKED.getType()) {
            // 若状态不正确，返回错误结果
            return YResult.error("项目对账状态非待核对");
        }

        // 更新结算状态为云采购已确认，并保存确认凭证和标记
        reconciliation.setStatus(ReconciliationStatusEnum.CHECKED_OUT.getType());
        reconciliation.setCheckFile(reconciliationFile);
        reconciliation.setCheckMark(reconciliationConfirmMark);
        iBamuReconciliationService.updateById(reconciliation);

        // 记录审核确认历史
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        Date date = ConvertUtil.getString2Date(reconciliationconfirmDate);
        iBamuAuditConfirmHistoryService.insertRecord(reconciliation.getId(), date
                , reconciliation.getReconciliationPrice(),
                reconciliationFile,
                reconciliationConfirmMark,
                ReconciliationStatusEnum.CHECKED_OUT.getType(), "0",
                userInfo.getRealName());

        // 返回操作成功的结果
        return YResult.success(reconciliation.getId());
    }

    @Override
    public YResult<String> ycconfirm(ReconciliationConfirmDto reconciliationConfirmDto) {
        // 提取DTO中的ID和其他确认信息
        String id = reconciliationConfirmDto.getId();
        String reconciliationconfirmDate =
                reconciliationConfirmDto.getReconciliationConfirmDate();
        String reconciliationConfirmPerson =
                reconciliationConfirmDto.getReconciliationConfirmPerson();
        String reconciliationFile =
                reconciliationConfirmDto.getReconciliationFile();
        String reconciliationConfirmMark =
                reconciliationConfirmDto.getReconciliationConfirmMark();


        if (!ConvertUtil.isValidNotEmptyJson(reconciliationFile)) {
            reconciliationFile = "[]";
        }
        // 根据ID获取结算信息，确保未被删除
        BamuReconciliation reconciliation =
                iBamuReconciliationService.getByIdNoDelete(id);
        if (Objects.isNull(reconciliation)) {
            // 若找不到结算信息，返回错误结果
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        // 检查结算状态是否为供应商已确认
        Integer status = reconciliation.getStatus();
        if (status != ReconciliationStatusEnum.CONFIRMED_BY_CLOUD_ACQUISITION.getType()) {
            // 若状态不正确，返回错误结果
            return YResult.error("项目对账状态非待云彩确认");
        }

        // 更新结算状态为云采购已确认，并保存确认凭证和标记
        reconciliation.setStatus(ReconciliationStatusEnum.CLOUD_ACQUISITION_CONFIRMATION_COMPLETE.getType());
        reconciliation.setYcConfirmDate(ConvertUtil.getString2Date(reconciliationconfirmDate));
        reconciliation.setYcConfirmPerson(reconciliationConfirmPerson);
        reconciliation.setYcFile(reconciliationFile);
        reconciliation.setYcConfirmMark(reconciliationConfirmMark);
        iBamuReconciliationService.updateById(reconciliation);

        // 记录审核确认历史
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        Date date = ConvertUtil.getString2Date(reconciliationconfirmDate);
        iBamuAuditConfirmHistoryService.insertRecord(reconciliation.getId(), date
                , reconciliation.getReconciliationPrice(),
                reconciliationFile,
                reconciliationConfirmMark,
                ReconciliationStatusEnum.CLOUD_ACQUISITION_CONFIRMATION_COMPLETE.getType(), "3",
                userInfo.getRealName());

        // 返回操作成功的结果
        return YResult.success(reconciliation.getId());
    }


    @Override
    public List<ReconciliationExcelDto> export(ReconciliationDto reconciliationDto) {
        //构建查询条件
        LambdaQueryWrapper<BamuReconciliation> queryWrapper = new LambdaQueryWrapper<>();
        // 处理status列表
        if (reconciliationDto.getStatusList() != null && !reconciliationDto.getStatusList().isEmpty()) {
            queryWrapper.in(BamuReconciliation::getStatus, reconciliationDto.getStatusList());
        }
        queryWrapper.eq(StringUtils.isNotBlank(reconciliationDto.getContractId()), BamuReconciliation::getContractId, reconciliationDto.getContractId())
                .eq(StringUtils.isNotBlank(reconciliationDto.getProjectId()), BamuReconciliation::getProjectId, reconciliationDto.getProjectId())
                .eq(StringUtils.isNotBlank(reconciliationDto.getSupplierDeptId()), BamuReconciliation::getSupplierDeptId, reconciliationDto.getSupplierDeptId())
                .eq(StringUtils.isNotBlank(reconciliationDto.getContractMethod()), BamuReconciliation::getContractMethod, reconciliationDto.getContractMethod())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuReconciliation::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuReconciliation::getSupplierDeptId, BaseContext.getSupplierList())
                .like(StringUtils.isNotBlank(reconciliationDto.getProjectName()), BamuReconciliation::getProjectName, reconciliationDto.getProjectName())
                .like(StringUtils.isNotBlank(reconciliationDto.getSupplierDeptName()), BamuReconciliation::getSupplierDeptName, reconciliationDto.getSupplierDeptName())
                .like(StringUtils.isNotBlank(reconciliationDto.getContractName()), BamuReconciliation::getContractName, reconciliationDto.getContractName())
                .like(StringUtils.isNotBlank(reconciliationDto.getContractNo()), BamuReconciliation::getContractNo, reconciliationDto.getContractNo())
                .ge(StringUtils.isNotBlank(reconciliationDto.getReconciliationStartDate()), BamuReconciliation::getReconciliationStartDate, ConvertUtil.getString2Date(reconciliationDto.getReconciliationStartDate()))
                .le(StringUtils.isNotBlank(reconciliationDto.getReconciliationEndDate()), BamuReconciliation::getReconciliationEndDate, ConvertUtil.getString2Date(reconciliationDto.getReconciliationEndDate()))
                .eq(reconciliationDto.getStatus() != null, BamuReconciliation::getStatus, reconciliationDto.getStatus())
                .eq(BamuReconciliation::getIsDeleted, 0)
                .orderByDesc(BamuReconciliation::getCreatedAt);
        List<BamuReconciliation> contractMaterialList = iBamuReconciliationService.list(queryWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(contractMaterialList)) {
            return contractMaterialList.stream().map(this::convertToExcelDto).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 将BamuContractMaterial转化成ContractMaterialExportDto
     */
    private ReconciliationExcelDto convertToExcelDto(BamuReconciliation bamuSpReconciliation) {
        ReconciliationExcelDto dto = new ReconciliationExcelDto();
        BeanUtils.copyProperties(bamuSpReconciliation, dto);
        dto.setId(bamuSpReconciliation.getId());
        return dto;
    }
}
